package com.example.demo6.controller;

import com.example.demo6.domain.Actor;
import com.example.demo6.domain.Role;
import com.example.demo6.repository.ActorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.text.SimpleDateFormat;

@Controller
@RequestMapping(value = "/actor")
public class ActorController {

    @Autowired
    private ActorRepository actorRepository;
    @RequestMapping(value = {"detail/{id}"})
    public String actor(Model model,@PathVariable Long id){
        Actor actor = actorRepository.findOne(id);
        model.addAttribute("actor", actor);
        return "actor/detail";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET )
    public String toEditActor(Model model,@PathVariable Long id){
        Actor actor = actorRepository.findOne(id);
        model.addAttribute("actor",actor);
        return "actor/edit";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST )
    public String doEditActor(@RequestParam Long id, @RequestParam String name,@RequestParam int sex,@RequestParam String born){
        Actor actor = actorRepository.findOne(id);
        actor.setName(name);
        actor.setSex(sex);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        Date data = null;
        try {
            data = simpleDateFormat.parse(born);
        } catch (Exception e) {
            e.printStackTrace();
        }
        actor.setBorn(data);
        actorRepository.save(actor);
        return "redirect:/actor/detail/"+actor.getId();
    }

}
